
<template>
  <div class="project-request-container">
    <div class="form">
      <el-row>
        <el-col :xs="24" :sm="24" :lg="24" class="border"></el-col>
      </el-row>
      <el-row class="choose" v-if="canEdit">
        <!-- <el-col :xs="24" :sm="24" :lg="24">
          <span style="float: right;">
            <el-button @click="formSave(true)" type="primary" class="newReport">提交</el-button>
          </span>
        </el-col> -->
      </el-row>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
             <span @click="showBaseInfo(false)" v-if="showBase" style="font-size:20px;cursor:pointer;" >基础信息<i class="el-icon-arrow-down el-icon--right"></i></span>
            <span @click="showBaseInfo(true)" v-if="!showBase" style="font-size:20px;cursor:pointer;">基础信息<i class="el-icon-arrow-up el-icon--right"></i></span>
            <span style="float: right;">
              <el-button @click="formSave(true)" type="primary" class="newReport">提交</el-button>
            </span>
          </div>
          <el-row v-if="showBase">

            <el-col :span="8">
              <div>
                <el-form-item label="项目名称" :required="true">
                  <el-input
                    v-model="form.project_name"
                    :disabled="mode != 'resourceCreate'"
                    placeholder="请输入项目名称"
                    :prefix-icon="projectIcon"
                    @change="handleProjectNameChanged"
                  ></el-input>
                </el-form-item>
                <el-form-item label="客户全称(原文)" :required="false">  
                  <el-autocomplete 
                    :disabled="!iscanEdit"  
                    class="inline-input"
                    v-model="form.customer_full_name"
                    :fetch-suggestions="querySearchCustomer"
                    placeholder="请输入客户全称或简称"
                    @select="handleSelectCustomer"
                    @input="handleCustomerChanged"
                    clearable
                  ></el-autocomplete>
                </el-form-item>
                <el-form-item label="所属事业部" :required="true">
                  <el-autocomplete
                    class="inline-input"
                    v-model="form.business_department"
                    :fetch-suggestions="querySearchDepartment"
                    placeholder="请输入事业部名或拼音"
                    @select="handleSelectDepartment"
                    @input="handleDepartmentChanged"
                    :disabled="!iscanEdit"
                    clearable
                  ></el-autocomplete>
                </el-form-item>
                <el-form-item label="所属事业群">
                  <el-input v-model="form.business_group" readonly></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div>
                <el-form-item label="项目经理" :required="true">
                  <el-autocomplete
                    class="inline-input"
                    v-model="form.project_manager"
                    placeholder="请输入姓名或拼音"
                    :fetch-suggestions="querySearchAsync"
                    @select="handleSelectProjectManager"
                    :disabled="!iscanEdit"
                    clearable
                  >
                    <template slot-scope="{ item }">
                      <div class="name">{{ item.value }}_{{ item.ldap }}</div>
                    </template>
                  </el-autocomplete>
                </el-form-item>
                <el-form-item label="客户简称">
                  <el-input
                    v-model="form.customer_abrv_name"
                    :disabled="!iscanEdit"
                  ></el-input>
                </el-form-item>
                <el-form-item label="所属事业部负责人">
                  <el-input
                    v-model="form.business_department_manager"
                    readonly
                  ></el-input>
                </el-form-item>
                <el-form-item label="所属事业群负责人">
                  <el-input
                    v-model="form.business_group_manager"
                    readonly
                  ></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div>
                <el-form-item label="需求类型" :required="false">
                  <el-select
                      v-model="form.demand_type"
                      placeholder="选择需求类型"
                      style="width: 105px"
                      :disabled="!iscanEdit"
                    >
                      <el-option label="全体" value="全体"></el-option>
                      <el-option label="仅Offshore" value="仅Offshore"></el-option>
                      <el-option label="Offshore+ODC" value="Offshore+ODC"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="客户等级">
                  <el-col>
                    <el-input
                      v-model="form.customer_level"
                      :disabled="!iscanEdit"
                    ></el-input>
                  </el-col>
                </el-form-item>
                <el-form-item label="项目开始日期" :required="true">
                  <el-col>
                    <el-date-picker
                      type="date"
                      placeholder="选择日期"
                      value-format="yyyy-MM-dd"
                      v-model="form.project_start_date"
                      style="width: 100%;"
                      :disabled="!canEdit || !dateEdit || !iscanEdit"
                      @change="startchange($event)"
                    ></el-date-picker>
                  </el-col>
                </el-form-item>
                <el-form-item label="项目结束日期" :required="true">
                  <el-col>
                    <el-date-picker
                      @change="projectEndDateChanged"
                      type="date"
                      placeholder="选择日期"
                      value-format="yyyy-MM-dd"
                      v-model="form.project_end_date"
                      style="width: 100%;"
                      :disabled="!canEdit || !dateEdit || !iscanEdit"
                    ></el-date-picker>
                  </el-col>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>工数预测</span>
            <div class="tip">tip:双击任一周/月即可设定为项目起始周/月和结束周/月，可以批量填写工数</div>
          </div>
          <el-row>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-button-group>
                  <el-button type="primary" :class="showWeek?'btnColorL':'btnColorN'" @click="showWeekFn(true)">按周填写</el-button>
                  <el-button type="primary" :class="showWeek?'btnColorN':'btnColorL'" @click="showWeekFn(false)">按月填写</el-button>
                </el-button-group>
                   <el-button style="float:right;margin-left:5px" type="success" class="btn-add" size="medium"  @click="checkNewform()">更新日志</el-button>
                   <el-button style="float:right" type="warning" class="btn-add" size="medium" icon="el-icon-plus" :disabled="hasAddModel" @click="addManPowerRow()">增加</el-button>
                   <el-table :data="manPowerList" border style="width: 100%"
                    id="tableMan"
                    :row-class-name="tableRowIndex"
                    v-if="showTable"
                    show-summary
                    :summary-method="getSummaries"
                    :cell-style="tableCellStyle"
                    @cell-dblclick="selectCell"
                    v-loading="loadingManPowerMon"
                    max-height = '500'
                    :key="Math.random()">
                    <template v-if="showWeek">
                    <el-table-column
                      align="center"
                      :key="v.field"
                      v-for="v in manPowerColumns"
                      :prop="v.field"
                      :fixed="v.fixed"
                      :label="v.title"
                      :width="v.width?v.width:''"
                      :min-width="v.min?v.min:''"
                    >
                      <template slot-scope="scope">
                        <span v-if="v.field == 'id'">{{ scope.$index + 1 }}</span>
                        <el-select
                          v-if="v.field == 'dept_id'"
                          size="mini"
                          v-model="scope.row[v.field]"
                          filterable
                          placeholder="请选择"
                          :disabled="!scope.row.editModel"
                        >
                          <el-option
                            v-for="item in departmentsFilter"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          >
                          </el-option>
                        </el-select>
                        <el-tooltip  placement="top" v-if="v.field == 'technical_field_ids'" effect='light'  >
                          <div slot="content" v-if="scope.row.technical_field_names">{{ scope.row.technical_field_names.join('/') }}</div>
                          <div slot="content" v-else>{{ '可选择一级技术领域' }}</div>
                          <el-cascader
                            v-model="scope.row[v.field]"
                            size="mini"
                            :options="techRangeFilter"
                            :disabled="!scope.row.editModel"
                            :props="{ checkStrictly: true }"
                            clearable ></el-cascader>
                        </el-tooltip>
                        <span v-if="v.field == 'man_month'">{{
                          sumManMonth(scope.row) | num45Filter
                        }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      :key="'week'+index"
                      type="cell"
                      :index="index"
                      v-for="(p, index) in estLabourWeek()"
                      :label="p.weeks+'周\n('+p.show+')'"
                      width="120"
                      align="center"
                      :prop="'week'+p.weeks">
                      <template slot-scope="scope">
                        <el-input
                          v-if="scope.row.editModel"
                          size="mini"
                          placeholder=""
                          v-model="scope.row.week_display_need[p.weeks]"
                          oninput="value=value.replace(/^0[0-9]|[^\d.]/g,'')"
                          @input="calculateTotalManMonth()"
                          :disabled="!canEdit"
                        >
                        </el-input>
                        <div v-else>
                          <div v-if="scope.row.week_display_need[p.weeks] == 0" style="color:red;margin-top: -26px;">
                            {{scope.row.week_display_need[p.weeks] | rounding}}
                          </div>
                          <div v-else style="margin-top: -26px;">
                            {{scope.row.week_display_need[p.weeks] | rounding}}
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                    </template>
                    <template v-if="!showWeek">
                      <el-table-column
                      align="center"
                      :key="v.field"
                      v-for="v in manPowerColumns1"
                      :prop="v.field"
                      :fixed="v.fixed"
                      :label="v.title"
                      :width="v.width?v.width:''"
                      :min-width="v.min?v.min:''"
                    >
                      <template slot-scope="scope">
                        <span v-if="v.field == 'id'">{{ scope.$index + 1 }}</span>
                        <el-select
                          v-if="v.field == 'dept_id'"
                          size="mini"
                          v-model="scope.row[v.field]"
                          filterable
                          placeholder="请选择"
                          :disabled="!scope.row.editModel"
                        >
                          <el-option
                            v-for="item in departmentsFilter"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          >
                          </el-option>
                        </el-select>
                        <el-tooltip  placement="top" v-if="v.field == 'technical_field_ids'" effect='light'  >
                          <div slot="content" v-if="scope.row.technical_field_names">{{ scope.row.technical_field_names.join('/') }}</div>
                          <div slot="content" v-else>{{ '可选择一级技术领域' }}</div>
                          <el-cascader
                            v-model="scope.row[v.field]"
                            size="mini"
                            :options="techRangeFilter"
                            :disabled="!scope.row.editModel"
                            :props="{ checkStrictly: true }"
                            clearable ></el-cascader>
                        </el-tooltip>
                        <span v-if="v.field == 'man_month'">{{
                          sumManMonth(scope.row) | num45Filter
                        }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      :key="'month'+index"
                      type="cell"
                      :index="index"
                      v-for="(m, index) in estLabourMonth()"
                      :label="m+'月'"
                      width="120"
                      align="center"
                      :prop="'month'+m"
                    >
                      <template slot-scope="scope">
                        <el-input
                          v-if="scope.row.editModel"
                          size="mini"
                          placeholder=""
                          v-model="scope.row.month_display_need[m]"
                          oninput="value=value.replace(/^0[0-9]|[^\d.]/g,'')"
                          :disabled="!canEdit"
                        >
                        </el-input>
                        <div v-else>
                          <div v-if="scope.row.month_display_need[m] == 0" style="color:red;margin-top: -21px;">
                            {{scope.row.month_display_need[m] | num45Filter}}
                          </div>
                          <div v-else style="margin-top: -21px;">
                            {{scope.row.month_display_need[m] | num45Filter}}
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                    </template>
                    
                    <el-table-column v-if="canEdit" align="center" fixed="right" label="操作" width="90">
                      <template slot-scope="scope">
                        <el-button v-if="scope.row.editModel" type="text" size="mini" @click="manPowerSave(scope.row,scope.$index,manPowerList)">
                          保存
                        </el-button>
                        <el-button v-if="scope.row.editModel" type="text" size="mini" @click="manPowerCancel(scope.row, scope.$index,manPowerList)">
                          取消
                        </el-button>
                        <el-button v-if="!scope.row.editModel" type="text" size="mini" @click="manPowerEdit(scope.row, scope.$index)">
                          修改
                        </el-button>
                        <el-button v-if="!scope.row.editModel" type="text" size="mini" @click="showFeishu(scope.row.id)">
                          通知
                        </el-button>
                        <el-popconfirm v-if="!scope.row.editModel" title="确定删除吗？" @onConfirm="manPowerDelete(scope.row, scope.$index,scope.row.id)">
                          <el-button slot="reference" type="text" size="mini" style="color: red;margin-left: 10px">
                            删除
                          </el-button>
                        </el-popconfirm>
                      </template>
                    </el-table-column>
                   </el-table>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
    </div>
    <el-dialog title="通知" :visible.sync="feishuVisible" width="800px" :destroy-on-close="true">
      <div>
        <el-form class="form-box" label-position="left">
            <el-row :gutter="20">
                <el-col :xs="24" :sm="24" :lg="24">
                    <template>
                        <el-form-item class="form-item" label="通知人员：">
                          <el-select
                            v-model="feishuMember"
                            multiple
                            filterable
                            remote
                            popper-append-to-body
                            style="width: 600px"
                            placeholder="请输入关键词"
                            :remote-method="queryAllMember"
                            :loading="loadingFeishu">
                            <el-option
                              v-for="item in feishuOptions"
                              :key="item.id"
                              :label="item.name"
                              :value="item.ldap">
                              <span style="float: left">{{ item.name }}</span>
                              <span style="float: right">{{ item.ldap }}</span>
                            </el-option>
                          </el-select>
                        </el-form-item>
                     </template>
                </el-col>
            </el-row>
        </el-form>
        <div class="form-btn">
            <el-button type="primary" @click="submitFeishu">保存</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="更新日志" :visible.sync="checkVisible" width="60%">
      <CheckNewdata v-if="checkVisible" :projectName = "projectName" ></CheckNewdata>
    </el-dialog>
  </div>
</template>
<script>
import pinyin from "pinyin";
import http from "@/views/sys/axios";
import { getHeaderName } from '@/app.config'
import lodash from "lodash";
import { DateUtil } from '../utils.js'
import checkNewdata from '../components/checkNewdata.vue'
export default {
  inject: ['reload'],
  name: "ProjectRequest",
  components: {
    CheckNewdata: checkNewdata
  },
  props: {
    formData: Object,
    mode: String
  },
  data() {
    return {
      projectName:'',
      checkVisible:false,
      showBase:false,
      showStartData:'',
      showEndData:'',
      showData : [],
      showWeek: true,
      iscanEdit:true,
      startData:'',
      endData:'',
      monthArr:[],
      nowResult:[],
      startArr:[],
      endArr:[],
      showArr:'',
      tableHeight:500,
      manLdap:'',
      tabName:'0',
      columnId:'',
      totalManMonth1:0,
      avgCostRMB1: 0,
      form: {},
      form_id: '',
      newId: '',
      base_form: {},
      canEdit: this.mode === "resourceCreate" || this.mode === "resourceEdit",
      loading: false,
      loadingManPower: false,
      loadingManPowerMon: false,
      btnLoadingW:false,
      btnLoadingM:false,
      loadingFeishu: false,
      upload_api:
        process.env.VUE_APP_SOURSE_MANAGE_HOST +
        "/api/base/workflow/upload_attachment",
      username: "",
      projectIcon: "el-icon-more",
      project_name_save: "",
      project_name_list: [],
      profit: 0,
      profit_rate: 0,
      state: "",
      timeout: null,
      totalManMonth: 0,
      avgCostRMB: 0,
      software_platforms: [],
      hardware_platforms: [],
      corporations: [],
      departments: [],
      roles: [],
      customers: [],
      selectedManPowerRow: null,
      activeIndex: "1",
      projectPeriod: 0,
      employees: [],
      application_types: [
        { label: "立项", value: 0 },
        { label: "变更", value: 1 },
      ],
      incomeCheckMethods: [
        { label: "履约进度法", value: 9 },
        { label: "结算单", value: 10 },
        { label: "商品销售法", value: 11 },
        { label: "无收入", value: 12 },
      ],
      productionOptions: [
        {
          value: "0",
          label: "Mobile",
          children: [
            {
              value: "0",
              label: "Mobile",
            },
            {
              value: "1",
              label: "Pad",
            },
            {
              value: "2",
              label: "家电类",
            },
            {
              value: "3",
              label: "Watch",
            },
            {
              value: "4",
              label: "智能系统",
            },
            {
              value: "5",
              label: "Others",
            },
          ],
        },
        {
          value: "5",
          label: "智能汽车产品",
          children: [
            {
              value: "21",
              label: "Kanzi & Kanzi Connect",
            },
            {
              value: "22",
              label: "Auto Test Tool",
            },
            {
              value: "23",
              label: "混合仪表固件",
            },
            {
              value: "24",
              label: "FOTA",
            },
            {
              value: "25",
              label: "QNX Hypervisor",
            },
            {
              value: "26",
              label: "Others",
            },
          ],
        },
        {
          value: "6",
          label: "智能汽车服务",
          children: [
            {
              value: "27",
              label: "智能驾驶舱软件开发服务",
            },
            {
              value: "28",
              label: "IVI软件测试服务",
            },
            {
              value: "29",
              label: "Kanzi HMI//MW-开发服务",
            },
            {
              value: "30",
              label: "Camera集成和Tuning",
            },
            {
              value: "31",
              label: "语音语义集成服务",
            },
            {
              value: "32",
              label: "Others",
            },
          ],
        },
        {
          value: "7",
          label: "智能汽车方案",
          children: [
            {
              value: "33",
              label: "Android IVI",
            },
            {
              value: "34",
              label: "Hypervisor Cockpit",
            },
            {
              value: "35",
              label: "Linux IVI",
            },
            {
              value: "36",
              label: "QNX Cluster",
            },
            {
              value: "37",
              label: "Info ADAS",
            },
            {
              value: "38",
              label: "Audio",
            },
            {
              value: "39",
              label: "SRV",
            },
            {
              value: "40",
              label: "手机互联方案",
            },
            {
              value: "41",
              label: "eAVB",
            },
            {
              value: "42",
              label: "Others",
            },
          ],
        },
        {
          value: "1",
          label: "IOT",
          children: [
            {
              value: "6",
              label: "AR/VR",
            },
            {
              value: "10",
              label: "Camera",
            },
            {
              value: "48",
              label: "Cloud-FOTA",
            },
            {
              value: "49",
              label: "Cloud-MDM",
            },
            {
              value: "50",
              label: "Face Access",
            },
            {
              value: "51",
              label: "Handy Terminal",
            },
            {
              value: "17",
              label: "NB&mini-IOT",
            },
            {
              value: "52",
              label: "New Retailing",
            },
            {
              value: "53",
              label: "Robotics",
            },
            {
              value: "9",
              label: "SmartHome",
            },
            {
              value: "11",
              label: "Smartspeaker",
            },
            {
              value: "16",
              label: "SOM",
            },
            {
              value: "15",
              label: "Wearable",
            },
            {
              value: "20",
              label: "Others",
            },
          ],
        },
        {
          value: "2",
          label: "Image/Graphics Algorithm",
        },
        {
          value: "3",
          label: "Security",
        },
        {
          value: "4",
          label: "Enterprise",
          children: [
            {
              value: "43",
              label: "MDM",
            },
            {
              value: "44",
              label: "FOTA",
            },
            {
              value: "45",
              label: "APP开发",
            },
            {
              value: "46",
              label: "智能系统",
            },
            {
              value: "47",
              label: "En.-Others",
            },
          ],
        },
      ],
      businessOptions: [
        {
          value: "0",
          label: "交付型业务",
          children: [
            {
              value: "0",
              label: "软件交付_NRE",
            },
            {
              value: "23",
              label: "硬件设计_NRE",
            },
            {
              value: "8",
              label: "软硬一体_含硬件试产",
            },
            {
              value: "11",
              label: "培训服务",
            },
            {
              value: "12",
              label: "其他",
            },
          ],
        },
        {
          value: "1",
          label: "人力型业务",
          children: [
            {
              value: "17",
              label: "现场人力服务",
            },
            {
              value: "18",
              label: "离岸人力服务",
            },
          ],
        },
        {
          value: "2",
          label: "硬件产品销售业务",
          children: [
            {
              value: "19",
              label: "硬件批量出货",
            },
            {
              value: "20",
              label: "硬件零售",
            },
          ],
        },
        {
          value: "3",
          label: "软件产品销售业务",
          children: [
            {
              value: "21",
              label: "软件产品零售",
            },
            {
              value: "2",
              label: "软件产品Royalty",
            },
            {
              value: "22",
              label: "软件授权或IP代理_IPLicense",
            },
          ],
        },
      ],
      exchangeRate: [
        {
          id: 12,
          currency_name: "林吉特",
          currency_code: "MYR",
          rate: 1.657,
        },
        {
          id: 11,
          currency_name: "卢比",
          currency_code: "INR",
          rate: 0.095,
        },
        {
          id: 10,
          currency_name: "韩币",
          currency_code: "KRW",
          rate: 0.006,
        },
        {
          id: 8,
          currency_name: "人民币",
          currency_code: "RMB",
          rate: 1.0,
        },
        {
          id: 7,
          currency_name: "欧元",
          currency_code: "EUR",
          rate: 7.787,
        },
        {
          id: 4,
          currency_name: "日元",
          currency_code: "JPY",
          rate: 0.065,
        },
        {
          id: 3,
          currency_name: "美元",
          currency_code: "USD",
          rate: 7.036,
        },
        {
          id: 1,
          currency_name: "新台币",
          currency_code: "NTD",
          rate: 0.235,
        },
      ],
      estCost: 0,
      estIncome: 0,
      estIncomeRaw: 0,
      rules: {},
      techRangeFilter: [],
      departmentsFilter: [],
      endWeek: '',
      startWeek: '',
      inpVal: '',
      selectWeekList: [],
      numShow: false,
      startCell: -1,
      startCell1: -1,
      endCell: -1,
      endCell1: -1,
      projectsList: [],
      activeName: '1',
      // 人力投入
      manPowerColumns: [
        {field: 'id', title: '#', width: 40 , fixed: 'left',},
        {
          field: 'dept_id',
          title: '实施部门',
          fixed: 'left',
          min: 160
        },
        // {field: 'role', title: '角色', min: 150},
        {field: 'technical_field_ids', title: '技术领域', fixed: 'left', min: 100},
        {field: 'man_month', title: '工数(人周)', fixed: 'left', width: 100},
      ],
      manPowerColumns1: [
        {field: 'id', title: '#', width: 40,fixed: 'left',},
        {
          field: 'dept_id',
          title: '实施部门',
          fixed: 'left',
          min: 160
        },
        // {field: 'role', title: '角色', min: 150},
        {field: 'technical_field_ids', title: '技术领域', fixed: 'left', min: 100},
        {field: 'man_month', title: '工数(人月)', fixed: 'left', width: 100},
      ],
      manPowerList: [],
      hasAddModel: false,
      dateEdit: true,
      feishuVisible: false,
      feishuMember:'',
      feishuOptions: [],
      feishuId: '',
      showTable: true,
      row:'',
      column:'',
      color:false,
      selectC:[],
      showweekend:'',
    };
  },
  watch: {
    projectPeriod() {
      this.projectPeriodChanged();
    },
  },
  filters: {
    rounding (value) {
      if(value || value === 0) { //这个判断是为了防止数据为空，页面渲染为NAN
        return Number(value).toFixed(1)
      }
    },
    numFilter(value) {
      let tempVal = parseFloat(value || 0).toFixed(3);
      let realVal = tempVal.substring(0, tempVal.length - 1);
      return realVal;
    },
    num45Filter(amount, decimalCount = 1, decimal = ".", thousands = ",") {
      try {
        decimalCount = Math.abs(decimalCount);
        decimalCount = isNaN(decimalCount) ? 2 : decimalCount;
        const negativeSign = amount < 0 ? "-" : "";
        let tempVal = Math.pow(10, 2);
        let i = parseInt(
          (amount = Math.abs(
            Number(Math.round(amount * tempVal) / tempVal) || 0
          ).toFixed(decimalCount))
        ).toString();
        let j = i.length > 3 ? i.length % 3 : 0;
        return (
          negativeSign +
          (j ? i.substr(0, j) + thousands : "") +
          i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) +
          (decimalCount
            ? decimal +
              Math.abs(amount - i)
                .toFixed(decimalCount).slice(2)
            : "")
        );
      } catch (e) {
        console.log(e);
      }
    },
  },
  created() {
    this.form = Object.assign({},this.formData)
    this.getname();
    this.getTechRange()
    this.getDepartment()
  },
  mounted() {
    this.projectsList = this.loadProject();
    this.customers = this.loadCustomers();
    this.software_platforms = this.loadSoftwarePlatforms();
    this.hardware_platforms = this.loadHardwarePlatforms();
    this.roles = this.loadRoles();
    this.employees = this.loadEmployees();
    this.corporations = this.loadCorporations();
    if (this.canEdit) {
      this.project_name_save = this.form.project_name;
    }
    if (this.mode != "resourceCreate") {
      this.dateEdit = this.$route.params.type
      this.getProjectDetail(this.$route.params.id)
    } else {
      this.getNewId()
    }
    if(this.mode == "resourceEdit") {
      this.activeName = '2'
    }
    // this.form.status = 0
    this.base_form = Object.assign({},this.form)
    // location.href="#posit"
  },
  destroyed() {},
  methods: {
    checkNewform(){
      this.checkVisible = true
    },
    showBaseInfo(flag){
      this.showBase = flag
    },
    showWeekFn(flag){
      if(this.hasAddModel) return this.$message.warning("请先保存修改/新增项目")
      if(flag){this.getManPowerList(this.$route.params.id)}
      this.showWeek = flag
    },
    handleClick(tab, event) {
      this.tabName = tab.name
    },
    showFeishu(id) {
      this.feishuVisible = true
      this.feishuId = id
    },
    queryAllMember(query) {
      if (query !== '') {
        this.loadingFeishu = true;
        setTimeout(() => {
            this.loadingFeishu = false;
            this.$axios({
                url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/employee/list?keywords=' + query,
                method: "get",
                headers: getHeaderName(),
            }).then(res => {
                this.feishuOptions = res.data.data
            })
        }, 200);
      } else {
          this.feishuOptions = [];
      }
    },
    submitFeishu() {
      if(this.feishuMember == '') {
        this.$message.error("通知人员不能为空");
        return false;
      }
      let localUrl = `http://${window.location.host}`
      let data = {
        'project_site_power_id': this.feishuId,
        'receive_ldap': this.feishuMember.join(),
        'card_link_url': localUrl
      }
      this.$axios({
        url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/demand/assign/remind`,
        method: "post",
        data: data,
        headers: getHeaderName(),
      }).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.message);
          this.feishuVisible = false
          this.feishuId = ''
          this.feishuMember == ''
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    getNewId() {
      this.$axios({
        url:
          process.env.VUE_APP_SOURSE_MANAGE_HOST +
          "/api/v1/project/uuid",
        method: "get",
        headers: getHeaderName(),
      }).then((res) => {
        this.newId = res.data.data
      });
    },
    canEditProjectName() {
      if (this.mode === "resourceCreate") {
        return true;
      } else {
        return false;
      }
    },
    tableRowIndex ({row, rowIndex}) {
      //把每一行的索引放进row
      row.index = rowIndex;  //拿到的索引赋值给row的index,在这个表格中能拿到row的里面都会包含index
      return ''  //className(类名)
    },
    tableCellStyle (row) {
      if(this.selectC.includes(row.row) && this.selectC.includes(row.column) && this.color ){
        return 'background-color:#13ce66;'
      } 
      else {
        return 'background-color:#fff;'
      }
    },
    selectCell(row, column, cell, event) {
      this.color = row.editModel
      if(this.color && column.type=='cell'){
        this.row = row
        this.column = column
        this.selectC.push(this.row,this.column)
        console.log("this.selectC1",this.selectC)
        this.selectC.length > 4 ? this.selectC = [] : this.selectC
        console.log("this.selectC2",this.selectC)
      }
      if(!row.editModel || column.type != 'cell') {
        return false
      }
      let index = row.index
      let colIndex = column.index
      let inputList = []
      if(this.showWeek){
        for(let key in row.week_display_need) {
          inputList.push({
            key: key,
            value: row.week_display_need[key]
          })
          this.compFnWeek(inputList)
        }
      }else {
         for(let key in row.month_display_need) {
          inputList.push({
            key: key,
            value: row.month_display_need[key]
          })
        }
        inputList=this.compFn(inputList)
      }
      let selectList = []
      if((this.startCell < 0 && this.endCell < 0) || (this.startCell >= 0 && this.endCell >= 0)) {
        this.startCell = colIndex
        this.endCell = -1
        inputList.map((v,i) => {
          if(i == colIndex) {
            selectList.push({
              key: v.key,
              value: true
            })
          } else {
            selectList.push({
              key: v.key,
              value: false
            })
          }
        })
      } else {
        this.endCell = colIndex
        let min = this.startCell <= this.endCell ? this.startCell : this.endCell
        let max = this.startCell <= this.endCell ? this.endCell : this.startCell
        let oldList = []
        inputList.map((v,i) => {
          oldList.push({
              key: v.key,
              value: false
            })
          if(i >= min && i <= max) {
            selectList.push({
              key: v.key,
              value: true
            })
          } else {
            selectList.push({
              key: v.key,
              value: false
            })
          }
        })
        this.numShow = true
        this.showData=[]
        selectList.map(val => {
        if(val.value == true) this.showData.push(val.key)
      })
        this.open(oldList,index)
      }
      row.selectList = selectList
      
    },
    //月份排序
    compFn(arr){
      arr.forEach(item=>{
        item.list=new Date(item.key).getTime()
      })
      arr.sort((a,b)=>{
          return a.list - b.list
      })
      return arr
    },
    //周排序
    compFnWeek(arr){
      arr.forEach(item=>{
        item.list=item.key.split('-')
        item.days=Number(item.list[0])*365+Number(item.list[1])*7
      })
      arr.sort((a,b)=>{
        return a.days -b.days
      })
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      //循环处理所有列数据
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        //将每列的所有数据数字化处理成一个数组
        const values = data.map(item => {
          if(column.type == 'cell') {
            if(this.showWeek) return Number(item.week_display_need[column.property.replace('week','').replace('month','')])
            else return Number(item.month_display_need[column.property.replace('week','').replace('month','')])
          } else {
             return NaN
          }
        });
        //当前列的所有数据全是数字类型时
        if (!values.every(value => isNaN(value))) {
          //将当前列数据数组中的所有值，从左到右依次累加处理
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return (parseFloat(prev) + parseFloat(curr)).toFixed(1);
            } else {
              return parseFloat(prev).toFixed(1)
            }
          }, 0);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    open(selectList,index) {
      this.$prompt('请输入工数'+'('+this.showData+')', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(\d+(\.\d+)?)$/,
        inputErrorMessage: '请填写大于0的数'
      }).then(({ value }) => {
        this.addAllManWeek(value)
        this.startCell = -1
        this.endCell = -1
        this.selectC = []
        this.manPowerList[index].selectList = selectList
      }).catch(() => {
        this.startCell = -1
        this.endCell = -1
        this.selectC = []
        this.manPowerList[index].selectList = selectList
      });
    },
    addAllManWeek(value) {
          this.manPowerList.map((item,index) => {
          if(item.selectList) {
            item.selectList.map((v,i) => {
              if(v.value) {
                this.showWeek?this.$set(item.week_display_need, v.key, value):this.$set(item.month_display_need, v.key, value)
              }
            })
          }
        })
    },
    getId(){
      this.$axios({
          url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/uuid`,
          method: "get",
          headers: getHeaderName(),
        }).then((res => {
          this.columnId = res.data.data
        }))
    },
    manPowerSave(row,index,rows) {
      if(this.form.project_name == '') {
        this.$message.error("项目名称不能为空");
        return false;
      }
      if(this.form.project_manager == '') {
        this.$message.error("项目经理不能为空");
        return false;
      }
      if(this.form.project_start_date == '') {
        this.$message.error("项目开始日期不能为空");
        return false;
      }
      if(this.form.project_end_date == '') {
        this.$message.error("项目结束日期不能为空");
        return false;
      }
      if(this.form.business_department == '') {
        this.$message.error("所属事业部不能为空");
        return false;
      }
      if(row.dept_id == '') {
        this.$message.error("实施部门不能为空");
        return false;
      }
      if(row.technical_field_ids == '') {
        this.$message.error("技术领域不能为空");
        return false;
      }
      row.editModel = false
      this.hasAddModel = false
      let pro_id = ''
      if(this.mode == 'resourceCreate') {
        pro_id = this.newId
      } else {
        pro_id = this.form_id
      }
      if(this.showWeek){
         let data = {
          dept_id: row.dept_id,
          project_workflow_id: pro_id,
          role: row.role,
          technical_field_ids: row.technical_field_ids,
          week_display_need: row.week_display_need,
          start_date: this.form.project_start_date,
          end_date: this.form.project_end_date,
          weekCol: this.form.weekCol,
          project_name: this.form.project_name
        }
        if(row.isAdd) {
          this.$axios({
            url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/demand`,
            method: "post",
            data: data,
            headers: getHeaderName(),
          }).then((res) => {
            if (res.data.code == 200 && res.data.status !== 'error') {
              this.formSave(false)
            } else if(res.data.status == 'error'){
              this.$message.error(res.data.message)
              rows.splice(index, 1)
              }else {
              this.$message.error(res.data.message);
              }
          });
        } else {
          this.$axios({
            url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/demand/${row.id}`,
            method: "post",
            data: data,
            headers: getHeaderName(),
          }).then((res) => {
            if (res.data.code == 200 && res.data.status !== 'error') {
              this.formSave(false)
            } else if(res.data.status == 'error'){
                this.$message.error(res.data.message)
                this.reload()
              }else {
              this.$message.error(res.data.message);
              this.reload()
            }
          });
        }
      }else{
        let data = {
          id:row.id || this.columnId,
          dept_id: row.dept_id,
          project_workflow_id: pro_id,
          role: row.role,
          technical_field_ids: row.technical_field_ids,
          start_date: this.form.project_start_date,
          end_date: this.form.project_end_date,
          json_data: row.month_display_need,
          weekCol: this.form.weekCol,
          project_name: this.form.project_name
        }
        if(row.isAdd) {
          
          this.$axios({
            url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/month_demand`,
            method: "post",
            data: data,
            headers: getHeaderName(),
          }).then((res) => {
            
            if (res.data.code == 200) {
              if(res.data.status === "error"){
                this.$message.error(res.data.message);
                rows.splice(index, 1)
              }else{
                this.formSave(false)
              }
            }
          });
        } else {
          console.log(987454564589)
          this.$axios({
            url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/month_demand`,
            method: "post",
            data: data,
            headers: getHeaderName(),
          }).then((res) => {
            
            if (res.data.code == 200 && res.data.status != "error") {
              this.formSave(false)
            } else if(res.data.status == 'error'){
                this.$message.error(res.data.message);
                this.getManPowerList(this.$route.params.id)
              }else {
              this.$message.error(res.data.message);
            }
          });
        }
      }
    },
    manPowerEdit(row,index) {
      row.editModel = true
      row.oldWeek = Object.assign({},row.week_display_need) 
      row.oldMon = Object.assign({},row.month_display_need) 
      let flag = false
      flag = flag || row.editModel
      this.hasAddModel = flag
    },
    manPowerCancel(row,index,rows) {
      if(row.isAdd){
        rows.splice(index, 1)
      }else{
        row.week_display_need = row.oldWeek
        row.month_display_need = row.oldMon
      }
      this.hasAddModel = false
      row.editModel = false
    },
    manPowerDelete(row,index,id) {
      let flag = false
      flag = flag || row.editModel
      if (flag) {
        this.$message.error("您有未保存的工数预测信息");
        return false;
      } else {
        let pro_id = ''
        if(this.mode == 'resourceCreate') {
          pro_id = this.newId
        } else {
          pro_id = this.form_id
        }
        this.$axios({
          url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/demand/${row.id}`,
          method: "delete",
          headers: getHeaderName(),
        }).then((res) => {
          if (res.data.code == 200) {
            this.$message.success(res.data.message);
            this.reload()
            // this.getManPowerList(pro_id)
          } else {
            this.$message.error(res.data.message);
          }
        });
      }
    },
    loadLocalFormData() {
      let localForm = localStorage.getItem("form");
      let localCalculated = localStorage.getItem("calculated");
      let formData = JSON.parse(localForm);
      let calculatedData = JSON.parse(localCalculated);
      if (localForm === null) {
        this.loading = false;
      } else {
        for (const d in formData) {
          this.form[d] = formData[d];
        }
        this.estCost = calculatedData.est_cost;
        this.estIncome = calculatedData.est_income;
        this.estIncomeRaw = calculatedData.est_income_raw;
        this.profit = calculatedData.profit;
        this.profit_rate = calculatedData.profit_rate;
        this.totalManMonth = calculatedData.total_man_month;
        this.avgCostRMB = calculatedData.avg_cost_RMB;
        this.loading = false;
        this.$notify.success("已载入保存数据");
      }
    },
    init_reckon() {
      console.log("init_reckon");
    },
    getdataPro() {
      //Cookies.set('name', name)
      return http.get(`/api/account/user/info`);
    },
    async getname() {
      try {
        const data = await this.getdataPro();
        this.username = data.data;
      } catch (err) {
        throw err;
      }
    },
    getManPowerList(id,week_col) {
      this.loadingManPowerMon = true
      this.$axios({
        url: `${process.env.VUE_APP_SOURSE_MANAGE_HOST}/api/v1/project/${id}/demand`,
        method: "get",
        headers: getHeaderName(),
      }).then((res) => {
        let response = res.data.data
        response.map((item,index) => {
          item.editModel = false
          this.$set(this.manPowerList, index, item)
        })
        this.hasAddModel = false
        this.loadingManPowerMon = false
        var showdate=new Date();
        var showyear = showdate.getFullYear();
        var showweekend1 = this.getYearWeek(showdate);
        this.showweekend = showyear + "-" +showweekend1  //当前周数
        if(response.length>0){
          let listArr = []
          for(let key in response[0].week_display_need){
            listArr.push({
              key:key,
            })
          }
          this.compFnWeek(listArr)
          for(let i = 0;i<listArr.length;i++){
            if(listArr[i].key == this.showweekend){
              let indexWeek = i
              setTimeout(() => {
                $('#tableMan').find('.el-table__body-wrapper')[0].scrollLeft = parseInt(indexWeek) * 120 
                this.loadingManPowerMon = false
                console.log($('#tableMan').find('.el-table__body-wrapper')[0].scrollLeft)
              },500)
            }else{this.loadingManPowerMon = false}
          }
        }else{this.loadingManPowerMon = false}
      });
    },
    getProjectDetail(id) {
        this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST +"/api/v1/project/" + id,
        method: "get",
        headers: getHeaderName(),
      }).then((res) => {
        this.projectName = res.data.data.form_data.project_name
        this.iscanEdit = res.data.data.can_edited
        this.startData = res.data.data.form_data.project_start_date
        this.endData = res.data.data.form_data.project_end_date
         this.initStartMonth()
         this.initEndtMonth()
        for (const d in res.data.data.form_data) {
          this.form[d] = res.data.data.form_data[d];
        }
        this.form.status = res.data.data.status
        this.getManPowerList(id,res.data.data.week_col)
      });
      this.form_id = id;
    },
    getExistProjectDetail(id) {
      // load data in view mode
      this.$axios({
        url:
          process.env.VUE_APP_PROJECT_REQUEST_HOST +
          "/api/base/project/apply?id=" + id,
        method: "get",
      }).then((res) => {
        if(res.data.code == 200) {
          for (const d in res.data.data.form) {
            this.form[d] = res.data.data.form[d];
          }
        }
      });
      this.form_id = id
    },
    getTechRange() {
      this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/filter/technical_field/tree',
        method: "get",
        headers: getHeaderName(),
      }).then(res => {
        this.techRangeFilter = res.data.data
      })
    },
    getDepartment() {
      let departments = [{}];
        this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST + '/api/v1/department/list',
        method: "get",
        headers: getHeaderName(),
      }).then(res => {
        this.departmentsFilter = res.data.data;
      }).catch((error) => {
        console.log(error);
      });
    },
    formSave(key) {
      let flag = false
      let flag1 = false
      if(key) {
        if(this.form.project_name == '') {
          this.$message.error("项目名称不能为空");
          return false;
        }
        if(this.form.project_manager == '') {
          this.$message.error("项目经理不能为空");
          return false;
        }
        if(this.form.project_start_date == '') {
          this.$message.error("项目开始日期不能为空");
          return false;
        }
        if(this.form.project_end_date == '') {
          this.$message.error("项目结束日期不能为空");
          return false;
        }
        if(this.form.business_department == '') {
          this.$message.error("所属事业部不能为空");
          return false;
        }
        this.manPowerList.map((item,ind) => {
          flag = flag || item.editModel
        })
      }
      if (flag || flag1) {
        this.$message.error("您有未保存的工数预测信息");
        return false;
      } else {
        var form_data = Object.assign({}, this.form);
        var pro_id = ''
        if(this.mode == 'resourceCreate') {
          pro_id = this.newId
        } else {
          pro_id = this.form_id
        }
        var data = {
            dept: this.form.business_department,	//是	string	立项事业部
            //project_type: this.form.status,	//是	string	项目类型
            project_name: this.form.project_name,	//是	string	项目名
            project_manager: this.form.project_manager,	//否	string	项目经理
            demand_type: this.form.demand_type,
            customer: this.form.customer_full_name,
            creator_name: this.username,	//否	string	创建人姓名
            status: this.form.status,
            form_data: form_data,
            id: pro_id,
            project_manager_ldap: this.manLdap
        };
        if(this.mode == 'resourceCreate') {
          this.$axios({
            url: process.env.VUE_APP_SOURSE_MANAGE_HOST + "/api/v1/project",
            method: "post",
            headers: getHeaderName(),
            data: data,
          }).then((res) => {
            if (res.data.code == 200) {
              this.$message.success("提交成功");
              if(key) {
                this.$router.push({ name: 'resourceForecast' })
              } else {
                this.$router.push({ name: 'resourceEdit', params: { id: pro_id } })
                console.log("pro_id",pro_id)
              }
            } else {
              this.$message.error(res.data.message);
            }
          });
        } else {
          this.$axios({
            url: process.env.VUE_APP_SOURSE_MANAGE_HOST + "/api/v1/project/" + this.$route.params.id,
            method: "post",
            headers: getHeaderName(),
            data: data,
          }).then((res) => {
            if (res.data.code == 200) {
              this.$message.success(res.data.message);
              if(key) {
                this.$router.push({ name: 'resourceForecast' })
              } else {
                this.getManPowerList(pro_id)
              }
            } else {
              // this.$message.error(res.data.message);
            }
          });
        }
      }
    },
    formReset() {
      localStorage.clear();
      this.$router.go(0);
    },
    getCalculated() {
      return {
        profit_rate:
          ((this.estIncome * this.form.currency - this.estCost) * 100) /
          this.estIncome,
        est_income: this.estIncome,
        total_man_month: this.totalManMonth,
        est_cost: this.estCost,
        est_income_raw: this.estIncomeRaw,
        profit: this.estIncome * this.form.currency - this.estCost,
        avg_cost_RMB: this.avgCostRMB,
        avg_income_RMB: this.totalManMonth
          ? this.est_income / this.totalManMonth
          : "0",
        submitter: this.username,
      };
    },
    isUndefined(para) {
      return para === void 0;
    },
    projectPeriodChanged() {
      let projectIncome = this.form.projectIncome;
      for (const i in projectIncome) {
        projectIncome[i].input = new Array(this.estLabourWeek().length).fill(
          0
        );
      }
      this.form.projectIncome = projectIncome;
    },
    calculateTotalManMonth() {
      let totalManMonth = 0;
      let list = this.manPowerList
      var sum = 0
      list.map((item) => {
        if (!item.total) {
          sum += this.sumManMonth(item)
        }
      });
      return sum;
    },
    loadProject(){
      this.$axios({
        url: process.env.VUE_APP_SOURSE_MANAGE_HOST +
        "/api/v1/project/list",
        method: "get",
        headers: getHeaderName(),
      }).then(
        (response) =>
            (this.projectsList = response.data.data.map((x) => {
              x.pinyin = pinyin(x.name, {
                style: pinyin.STYLE_NORMAL,
              }).join("");
              x.type = x.type || "";
              x.value = x.name || "";
              return x;
            }))
      );
    },
    querySearchProject(queryString, cb) {
      let restaurants = this.projectsList;
      let results = queryString ? restaurants.filter(this.createFilter1(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter1(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
            0 ||
          restaurant.type.toLowerCase().indexOf(queryString.toLowerCase()) === 0 ||
          restaurant.pinyin.indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    querySearchCustomer(queryString, cb) {
      let customers = this.customers;
      let results = queryString
        ? customers.filter(this.createFilter(queryString))
        : [];
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    querySearchCorporation(queryString, cb) {
      let corporations = this.corporations;
      let results = queryString
        ? corporations.filter(this.createFilterNameAndPinyin(queryString))
        : corporations;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    querySearchDepartment(queryString, cb) {
      let departments = [{}];
      this.$axios.get(`${process.env.VUE_APP_PROJECT_REQUEST_HOST}/api/base/department/`, {params: { format: 'json', search: queryString, level: 2 }
          })
          .then(response => {
              for (let i of response.data.data) {
                  i.value = i.name;
              }
              departments = response.data.data;
              cb(departments);
          })
          .catch(error => {
              console.log(error);
          });
    },
    createFilterName(queryString) {
      return (item) => {
        return (
          item.value.indexOf(queryString) >= 0 ||
          item.pinyin.indexOf(queryString.toLowerCase()) >= 0
        );
      };
    },
    createFilterNameAndPinyin(queryString) {
      return (item) => {
        return item.value.indexOf(queryString) === 0;
      };
    },
    createFilter(queryString) {
      return (customer) => {
        return (
          customer.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
            0 ||
          customer.abbr_name
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0 ||
          customer.pinyin.indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleCustomerChanged(customer) {
      // 清空客户相关表单
      if (typeof customer != "undefined" && customer === "") {
        this.form.customer_abrv_name = "";
        this.form.customer_region = "";
        this.form.customer_level = "";
        this.form.customer_category = "";
      }
    },
    handleProjectNameChanged() {
      if (this.canEdit && this.project_name_save == this.form.project_name) {
        this.projectIcon = "el-icon-check";
      } else {
        this.$axios({
          url:process.env.VUE_APP_SOURSE_MANAGE_HOST +
              "/api/v1/project/check/name",
          method: "post",
          headers: getHeaderName(),
          data: {
            name: this.form.project_name
          }
        }).then((response) => {
          if (this.form.project_name === "") {
            this.projectIcon = "el-icon-more";
          } else if (response.data.data.exist === true) {
            this.$message.error("项目已存在，请使用其它项目名");
            this.form.project_name = "";
            this.projectIcon = "el-icon-close";
          } else {
            this.projectIcon = "el-icon-check";
          }
        });
      }
    },
    handleSelectCurrency(item) {
      this.exchangeRate.map((v) => {
        if (v.id == item) {
          this.form.currency = v.rate;
        }
      });
    },
    handleSelectSales(item) {
      this.form.sales_id = item.id;
    },
    handleSelectProjectManager(item) {
      this.form.project_manager_id = item.id;
    },
    handleSelectProjectDirector(item) {
      this.form.project_director_id = item.id;
    },
    handleSelectCorporation(item) {
      this.form.corporation_id = item.id;
    },
    handleDepartmentChanged(department) {
      // 清空部门相关表单
      if (typeof department != "undefined" && department === "") {
        this.form.business_department_manager = "";
        this.form.business_department = "";
      }
      //添加收入拆分
      this.addIncomeDistributionRow(this.form.business_department);
    },
    selectProjectName(project) {
      this.$axios({
          url: process.env.VUE_APP_PROJECT_REQUEST_HOST +
          "/api/v1/project/details?project_name="+this.form.project_name,
          method: "get",
          headers: getHeaderName(),
        }).then((response) => {
          if (response.data.code == 200) {
            this.form.status = 1;
            this.form = response.data.data
          } else {
            this.form.status = 0;
          }
        });
    },
    handleSelectProjectName(project) {
        this.$axios({
          url: process.env.VUE_APP_SOURSE_MANAGE_HOST +
          "/api/v1/project/details?project_name="+this.form.project_name,
          method: "get",
          headers: getHeaderName(),
        }).then((response) => {
          if (response.data.code == 200) {
            if(project.type == 'history'){
              this.form = response.data.data
            }else{
              this.form = Object.assign({},this.base_form)
              this.form = Object.assign(this.form,response.data.data)
              this.projectEndDateChanged(response.data.data.project_end_date)
            }
          } else {
          }
        });
    },
    clearProjectName(){
      this.form = Object.assign({},this.base_form)
    },
    handleSelectCustomer(customer) {
      this.form.customer_abrv_name = customer.abbr_name;
      this.form.customer_level = customer.level;
      this.form.customer_category = customer.category;
      this.form.customer_region = customer.region;
    },
    handleSelectDepartment(department) {
      this.form.business_department_id = department.id;
      this.form.business_department_manager = department.manager;
      this.$axios
        .get(
          process.env.VUE_APP_PROJECT_REQUEST_HOST +
            "/api/base/business_group/search?department_id=" +
            department.id
        )
        .then((response) => {
          this.form.business_group_manager = response.data.data.manager;
          this.form.business_group = response.data.data.name;
        });
    },
    projectEndDateChanged(d) {
      if (this.form.project_start_date) {
        const end = new Date(d);
        var start = this.form.project_start_date;
        start = new Date(start.toString().replace(/-/g, "/"));
        const duration = end.getTime() - start.getTime();
        const monthDuration = duration / (24 * 60 * 60 * 30 * 1000);
        let projectPeriod = Math.floor(monthDuration * 10) / 10;
        this.projectPeriod = this.form.project_period = projectPeriod;
        let weekCol = this.estLabourWeek()
        let list = this.manPowerList
        list.map((item,index) => {
          let weekSave = {}
          weekCol.map((item1,index1) => {
            if(item.week_display_need[item1.weeks]) {
              weekSave[item1.weeks] = item.week_display_need[item1.weeks]
            } else {
              weekSave[item1.weeks] = '0'
            }
          })
          item.week_display_need = Object.assign({},weekSave)
          this.$set(this.manPowerList, index, item)
        })
      }
      // 结束月份
      this.endArr=[]
      let endTime =new Date(d)
      this.endArr.push(endTime.getFullYear())
      this.endArr.push(endTime.getMonth() + 1)
      this.endArr.push(endTime.getDate() )
      this.nowResult=this.estLabourMonth()
    },
    // 开始月份
    startchange(e){
      this.startArr=[]
      let startTime =new Date(e)
      this.startArr.push(startTime.getFullYear())
      this.startArr.push(startTime.getMonth() + 1)
      this.startArr.push(startTime.getDate() )
      this.nowResult=this.estLabourMonth()
    },
    estLabourMonth(){
      let result =[]
      if(this.startArr.length!=0 && this.endArr.length!=0){
        // 不同年
        if(this.endArr[0]>this.startArr[0]){
          // 跨度大于一年
          if(this.endArr[0]-this.startArr[0]>0){
            let years=this.endArr[0]-this.startArr[0]
            // 开始时间
            for(var i =this.startArr[1];i<=12;i++){
              result.push(this.startArr[0]+'-'+i)
            }
            // 中间时间
            if(years>1){
              for(var k = 1;k < years; k++){
                for(var o =1;o <= 12; o++){
                  result.push(Number(this.startArr[0]) + Number(k) +'-'+o)
                }
              }
            }
            // 结束时间
            for(var j=1;j<=this.endArr[1];j++){
              result.push(this.endArr[0]+'-'+j)
            }
          }
        }
        // 跨度在一年之内
        let p1 = ''
        if(this.endArr[0]==this.startArr[0]){
          for(var p=Number(this.startArr[1]);p<=Number(this.endArr[1]);p++){
            result.push(this.endArr[0]+'-'+p)
            p1 = p
          }
        }
      }
      return result
    },
    //页面初始化月份
    initStartMonth(){
      // this.nowResult=this.estLabourMonth()
      this.startArr=[]
      this.startArr = this.startData.split("-")
        this.startArr = this.startArr.map(function(val) {
          if (val[0] == "0") {
            return (val = val.slice(1));
          } else {
            return val;
          }
        });
      this.nowResult=this.estLabourMonth()
    },
    initEndtMonth(){
      this.endArr=[]
      this.endArr = this.endData.split('-')
      this.endArr = this.endArr.map(function(val) {
        if (val[0] == "0") {
          return (val = val.slice(1));
        } else {
          return val;
        }
      });
      this.nowResult=this.estLabourMonth()
    },
    // 计算当天所在周
    getYearWeek(endDate) {
        const startWeek = new Date(endDate); 
        let weekDate = new Date(endDate.getFullYear(), 0, 1); 
        let weekbd = weekDate.getDay() >= 4 ? (weekDate.getDay() - 7) : weekDate.getDay()
        let beginWeekDate = Math.ceil((parseInt((startWeek - weekDate) / (24 * 60 * 60 * 1000)) + 1 + weekbd) / 7); //日期在当年的周数
        return beginWeekDate
    },
    estLabourWeek() {
      const weeks = []
      const weekCol = []
      const start = new Date(this.form.project_start_date); //起始日期
      const end = new Date(this.form.project_end_date); //结束日期
      let beginDate = new Date(start.getFullYear(), 0, 1); //起始日期年份的第一天
      let endnDate = new Date(end.getFullYear(), 0, 1); //结束日期年份的第一天
      let bd = beginDate.getDay() >= 4 ? (beginDate.getDay() - 7) : beginDate.getDay()
      let ed = endnDate.getDay() >= 4 ? (endnDate.getDay() - 7) : endnDate.getDay()
      let beginWeek = Math.ceil((parseInt((start - beginDate) / (24 * 60 * 60 * 1000)) + 1 + bd) / 7); //起始日期在当年的周数
      let endWeek = Math.ceil((parseInt((end - endnDate) / (24 * 60 * 60 * 1000)) + 1 + ed) / 7); //结束日期在当年的周数
      let startWeek = beginWeek
      let startYear = start.getFullYear()
      if(start.getFullYear() == end.getFullYear()) {
        if(startWeek == 0) {
          let dateb11 = new Date(startYear-1+'-01-01 00:00:00')
          let date11 = new Date(startYear+'-01-01 00:00:00')
          let date1231 = new Date(startYear-1+'-01-01 00:00:00')
          let beforeWeek = Math.ceil((parseInt((date11 - date1231) / (24 * 60 * 60 * 1000)) + 1 + (dateb11.getDay() >= 4 ? (dateb11.getDay() - 7) : dateb11.getDay())) / 7); //起始年份前一年最后一天在当年的周数
          weeks.push({
            weeks: startYear-1 + "-" + beforeWeek,
            show: this.weekToDate(startYear-1,beforeWeek,5)
          });
          weekCol.push(startYear-1 + "-" + beforeWeek)
          startWeek++;
        }
        while (startWeek <= endWeek) {
          let daten11 = new Date(end.getFullYear()+1+'-01-01 00:00:00')
          let nextWeek = Math.ceil((parseInt((new Date(end.getFullYear()+1, 0, 1) - endnDate) / (24 * 60 * 60 * 1000)) + 1 + ed) / 7) //结束年份最后一天在当前年份的周数
          let str,show
          if(startWeek == nextWeek && daten11.getDay() < 4) {
              str = start.getFullYear()+1 + "-1"
              show = this.weekToDate(start.getFullYear()+1,1,5)
          } else {
              str = start.getFullYear() + "-" + startWeek
              show = this.weekToDate(start.getFullYear(),startWeek,5)
          }
          weeks.push({
            weeks: str,
            show: show
          });
          weekCol.push(str)
          startWeek++;
        }
      } else {
        while (startYear <= end.getFullYear()) {
          let dayMS=24*60*60*1000
          let betDay = new Date(startYear+1+'-01-01 00:00:00').getTime() - new Date(startYear+'-01-01 00:00:00').getTime()
          let newD1 = new Date(startYear,0,1)
          let newD2 = new Date(startYear,11,31)
          let betWeek = betDay / dayMS  - (newD2.getDay()+1) - (7-newD1.getDay())
          let day = 0
          if(newD1.getDay() < 4 && newD1.getDay() > 0) {
              day += 1
          }
          if(newD2.getDay() >= 4 || newD2.getDay() == 0) {
              day += 1
          }
          day += (betWeek / 7)
          for(let i = 1; i<=day; i++) {
            if((startYear == start.getFullYear() && i >= startWeek) || (startYear > start.getFullYear() && startYear < end.getFullYear()) || (startYear == end.getFullYear() && i <= endWeek)) {
              let str = startYear + "-" + i
              let show = this.weekToDate(startYear,i,5)
              weeks.push({
                weeks: str,
                show: show
              });
              weekCol.push(str)
            }
          }
          startYear++
        }
      }
      this.form.weekCol = weekCol
      return weeks
    },
    weekToDate(year,week,day) {
      let betDay = new Date(year+1+'-01-01 00:00:00').getTime() - new Date(year+'-01-01 00:00:00').getTime()
      let newD1 = new Date(year,0,1)
      let newD2 = new Date(year,11,31)
      let dayMS=24*60*60*1000
      let firstDay=firstDay=(7-newD1.getDay())*dayMS
      let weekMS=0
      if(newD1.getDay() < 4) {
         weekMS=(week-2)*7*dayMS
      } else {
        weekMS=(week-1)*7*dayMS
      }
      let result=newD1.getTime()+firstDay+weekMS+day*dayMS
      newD1.setTime(result)
      return newD1.getFullYear() + "/" + (newD1.getMonth()+1) + "/" +newD1.getDate()
    },
    addManPowerRow() {
      if(this.showWeek){
        let obj = {}
        let weeks = this.estLabourWeek()
        weeks.map((v,i) => {
          obj[v.weeks] = '0'
        })
        let j = {
          dept_id: '',
          id: '',
          role: '',
          technical_field_ids: '',
          week_display_need: obj,
          man_month: 0,
          editModel: true,
          isAdd: true
        };
        this.manPowerList.push(j);
        let flag = false
        this.manPowerList.map((item,ind) => {
            flag = flag || item.editModel
        })
        this.hasAddModel = flag
      }else{
        this.getId()
        let obj1 = {}
        let months = this.estLabourMonth()
        months.map((v1,i1) => {
          obj1[v1] = '0'
        })
        let j = {
          dept_id: '',
          id: '',
          role: '',
          technical_field_ids: '',
          month_display_need: obj1,
          man_month: 0,
          editModel: true,
          isAdd: true
        };
        this.manPowerList.push(j);
        let flag = false
        this.manPowerList.map((item,ind) => {
            flag = flag || item.editModel
        })
        this.hasAddModel = flag
      }
    },
    addIncomeDistributionRow(bu) {
      if (bu) {
        this.form.incomeDistribution = [];
      }
      let rowCount = this.form.incomeDistribution.length;
      let j = {
        id: rowCount + 1,
        implement_department: bu || "",
        type: bu ? "bu" : "",
        percentage: bu ? 25 : 0,
        income: 0,
      };
      this.form.incomeDistribution.push(j);
    },
    sumManMonth(row) {
      let sum = 0
      if(this.showWeek){
        for(let key in row.week_display_need){
          sum += parseFloat(row.week_display_need[key] || 0)
        }
      }else {
        for(let key in row.month_display_need){
          sum += parseFloat(row.month_display_need[key] || 0)
        }
      }
      
      return sum;
    },
    sumManMonthPerM(ind) {
      let list = this.manPowerList
      var sum = 0
      list.map((item) => {
        if (!item.total) {
          sum += parseFloat(item.week_display_need[ind] || 0)
        }
      });
      return sum;
    },
    querySearchAsync(queryString, cb) {
      let employees = [];
      if(queryString) {
        this.$axios
        .get(
          process.env.VUE_APP_PROJECT_REQUEST_HOST +
            "/api/base/employee/?format=json&search=" +
            queryString
        )
        .then((response) => {
          for (let i of response.data.data) {
            i.value = i.name;
            this.manLdap = i.ldap
          }
          employees = response.data.data;
          cb(employees);
        })
        .catch((error) => {
          console.log(error);
        });
      } else {
        cb(employees);
      }
    },
    loadCustomers() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/customer/?format=json")
        .then(
          (response) =>
            (this.customers = response.data.map((x) => {
              x.pinyin = pinyin(x.full_name, {
                style: pinyin.STYLE_NORMAL,
              }).join("");
              x.abbr_name = x.abbr_name || "";
              x.value = x.full_name;
              return x;
            }))
        );
    },
    loadProjectName() {
      this.$axios({
        url: process.env.VUE_APP_PROJECT_REQUEST_HOST + '/api/base/project',
        method: "get",
        params: {
          "page":this.tableCurrent,
          "per_page":this.tableSize,
          "ldap":this.ldap
        }
      }).then(res => {
        this.tableData = res.data.data
        this.tableTotal = res.data.total
      })
    },
    loadSoftwarePlatforms() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/sw_platform/?format=json")
        .then((response) => (this.software_platforms = response.data));
    },
    loadHardwarePlatforms() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/hw_platform/?format=json")
        .then((response) => (this.hardware_platforms = response.data));
    },
    loadRoles() {
      this.$axios
        // .get('http://127.0.0.1:8000/api/base/role/?format=json')
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/role/?format=json")
        .then((response) => (this.roles = response.data.data));
    },
    loadEmployees() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/employee/?format=json")
        .then((response) => (this.employees = response.data.data));
    },
    loadCorporations() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/corporation/?format=json")
        .then(
          (response) =>
            (this.corporations = response.data.data.map((x) => {
              x.pinyin = pinyin(x.name, {
                style: pinyin.STYLE_NORMAL,
              }).join("");
              x.value = x.name;
              return x;
            }))
        );
    },
    loadDepartments() {
      this.$axios
        .get(process.env.VUE_APP_PROJECT_REQUEST_HOST + "/api/base/department/?format=json")
        .then(
          (response) =>
            (this.departments = response.data.data.map((x) => {
              x.pinyin = pinyin(x.name, {
                style: pinyin.STYLE_NORMAL,
              }).join("");
              x.value = x.name;
              return x;
            }))
        );
    },
    calculateDepreciation() {
      let depreciation = this.form.depreciation;
      let manmonthList = []; //人月
      let list = this.form.manPowerInput;
      var sum = [];
      //保存结果的数组
      var result = [];
      list.map((item) => {
        if (!item.total) {
          sum.push(item.input);
        }
      });
      for (var key in sum) {
        //遍历数组的每一项
        $.each(sum[key], function(index, val) {
          if (result[index] == null || result[index] == "") {
            result[index] = 0;
          }
          result[index] += parseFloat(val || 0);
        });
      }
      if (this.form.manPowerInput.length) {
        this.form.manPowerInput[
          this.form.manPowerInput.length - 1
        ].input = result;
        manmonthList = result;
      }
      let assets = [];
      let immaterial = [];
      this.form.assets.map((item2) => {
        this.estLabourWeek().map((v, i) => {
          assets[i] =
            parseFloat(item2.input[i] || 0) + parseFloat(assets[i] || 0);
        });
      });
      this.form.immaterial.map((item3) => {
        this.estLabourWeek().map((v, i) => {
          immaterial[i] =
            parseFloat(item3.input[i] || 0) + parseFloat(immaterial[i] || 0);
        });
      });
      this.estLabourWeek().map((v, i) => {
        depreciation.map((item4, i4) => {
          if (item4.field == "rent") {
            item4.input[i] =
              parseFloat(this.form.constants.depreciation_rent || 0) *
              parseFloat(manmonthList[i] || 0);
          }
          if (item4.field == "computer") {
            item4.input[i] =
              (parseFloat(this.form.constants.depreciation_computer || 0) *
                parseFloat(manmonthList[i] || 0)) /
              36;
          }
          if (item4.field == "renovation") {
            item4.input[i] =
              parseFloat(this.form.constants.depreciation_renovation || 0) *
              parseFloat(manmonthList[i] || 0);
          }
          if (item4.field == "house") {
            item4.input[i] =
              parseFloat(this.form.constants.depreciation_house || 0) *
              parseFloat(manmonthList[i] || 0);
          }
          if (item4.field == "fixed_assets") {
            item4.input[i] =
              parseFloat(assets[i] / 36) + parseFloat(item4.input[i - 1] || 0);
          }
          if (item4.field == "intangible_assets") {
            item4.input[i] =
              parseFloat(immaterial[i] / 24) +
              parseFloat(item4.input[i - 1] || 0);
          }
          this.$set(this.form.depreciation, i4, depreciation[i4]);
        });
      });
      this.calculateTotalCost();
      this.profit = this.estIncome * this.form.currency - this.estCost;
      if (this.estCost) {
        this.profit_rate =
          ((this.estIncome * this.form.currency - this.estCost) * 100) /
          this.estIncome;
      }
      if (this.totalManMonth && this.totalManMonth != 0) {
        this.avgCostRMB = this.estCost / this.totalManMonth;
      }
    }
  },
};
</script>
<style lang="scss" scoped>
/deep/ .el-input.is-readonly {
  background-color: #f5f7fa;
  border-color: #dfe4ed;
  color: #ff6363;
  cursor: not-allowed;
}
/deep/ .el-table .cell {
  white-space: pre-line;
}
/deep/ .el-table td.cell-grey {
  background-color:#909399 !important;
  color: #fff;
}
/deep/ .el-table td.cell-red {
  background-color:#ff4949 !important;
  color: #fff;
}
/deep/ .el-table td.cell-yellow {
  background-color:#ffba00 !important;
  color: #fff;
}
/deep/ .el-table td.cell-green {
  background-color:#13ce66 !important;
  color: #fff;
}
/deep/.el-table__body-wrapper{
    z-index: 2
}
.form-box {
    min-height: 200px;
}
.form-btn {
    text-align: right;
}
.btnColorL{
  color: #fff;
  background-color: #1890ff;
  border-color: #1890ff;
}
.btnColorN{
  color: #fff;
  background-color: #8cc8ff;
  border-color: #8cc8ff;
}
.tip {
  float: right;
  line-height: 36px;
  font-size: 14px;
  color: #6f6f6f;
}
.box-card {
  margin-bottom: 20px;
}
.border {
  box-sizing: content-box;
  height: 0;
  overflow: visible;
  margin-top: 1rem;
  margin-bottom: 1rem;
  border: 0;
  border-top: 1px solid rgba(0, 0, 0, .1);
}
.primary {
  color: #409EFF;
  font-size: 30px;
  font-weight: 400;
}
.table-form {
  margin-bottom: 0;
}
.table-form /deep/ .el-form-item__error {
  position: relative;
}
.form {
  margin-bottom: 180px;
}
.inline-input {
  width: 100%;
}
.request-submit {
  //width: 1140px;
  position: fixed;
  z-index: 998;
  padding: 15px 25px 15px 200px;
  bottom: 36px;
  height: 120px;
  border-top: 1px solid #dbe3e4;
  background-color: #fff;
  box-shadow: 0 -4px 4px -2px #e4e9f8;
  left: 54px;
  right: 0;
}
.el-select .el-input {
  width: 110px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.label-item {
  margin-bottom: 8px;
  display: block;
}
.label-item:first-child {
  margin-bottom: 8px;
  display: block;
}
.label-item .label {
  width: 180px;
  text-align: right;
  display: inline-block;
  margin-right: 15px;
  color: #666;
}
.label-item .detail {
  display: inline-block;
}
.operations {
  display: inline-block;
  text-align: right;
  width: 8%;
}
.input-platform {
  margin-right: 15px;
}
.cost-about {
  display: inline-block;
  width: 30%;
  vertical-align: top;
  border-left: 1px solid #ddd;
  padding-right: 10px;
  box-sizing: border-box;
}
.cost-about:first-child {
  display: inline-block;
  width: 30%;
  border: none;
  vertical-align: top;
  padding-right: 10px;
  box-sizing: border-box;
}
.cost-about .cost-price .price {
  font-size: 18px;
  font-weight: 700;
  color: #ed711f;
}
.project-request-container {
  //min-width: 1140px;
  margin: 45px;
}
h3.project-title {
  color: rgb(31, 47, 61);
  font-weight: 400;
  font-size: 22px;
}
.btn-add {
  margin-bottom: 15px;
}
.btn-all {
  margin-bottom: 15px;
  float: right;
}
.el-row {
  // margin-bottom: 20px;
}
.el-col {
  border-radius: 4px;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
}
</style>
